package com.yokead.common;

import cn.jiangzeyin.StringUtil;
import com.yokead.shield.ShieldUtil;
import com.yokead.system.log.SystemLog;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.apache.velocity.util.ClassUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jiangzeyin
 * Created by jiangzeyin on 2017/1/5.
 */
public class FileResourceLoader extends ResourceLoader {
    private static final Map<String, Long> fileLastModified = new HashMap<>();

    @Override
    public void init(ExtendedProperties configuration) {
    }

    @Override
    public InputStream getResourceStream(String source) throws ResourceNotFoundException {
        String vmSource = StringUtil.clearPath("/vm/" + source);
        InputStream inputStream;
        inputStream = ClassUtils.getResourceAsStream(this.getClass(), vmSource);
        if (inputStream != null)
            return inputStream;
        File file = getResourceFile(source);
        if (!file.exists() && !file.isFile())
            return null;
        try {
            fileLastModified.put(source, file.lastModified());
            return new FileInputStream(file);
        } catch (FileNotFoundException e1) {
            SystemLog.ERROR().error("获取资源错误" + source, e1);
        }
        return null;
    }

    @Override
    public boolean isSourceModified(Resource resource) {
        long lastModified = resource.getLastModified();
        if (lastModified == 0)
            return false;
        File file = getResourceFile(resource.getName());
        return lastModified != file.lastModified();
    }

    @Override
    public long getLastModified(Resource resource) {
        Long time = fileLastModified.get(resource.getName());
        if (time == null)
            return 0;
        return time;
    }

    private File getResourceFile(String name) {
        String file = StringUtil.clearPath(ShieldUtil.getShieldConfPath() + "/" + name);
        return new File(file);
    }
}
